package com.hotel.controller;

import com.hotel.pojo.User;
import com.hotel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    /**
     * 查询全部，返回到用户展示页面
     * @return
     */
    @RequestMapping("/all")
    public String getAll(Model model){
        List<User> userList = userService.getAll();
        model.addAttribute("allUser",userList);
        System.out.println(userList);
        return "allUser";
    }

    /**
     * 跳转到增加用户页面
     */
    @RequestMapping("/toAddUser")
    public String toAddUser(){
        return "addUser";
    }

    //添加用户的请求
    @RequestMapping("/addUser")
    public String addUser(User user){
        userService.addUser(user);
        return "redirect:/user/all";//重定向
    }

    //跳转到修改页面
    @RequestMapping("/toUpdateUser")
    public String toUpdateUser(int id,Model model){
        User user = userService.selectUserById(id);
        model.addAttribute("user",user);
        return "updateUser";
    }

    //修改用户的请求
    @RequestMapping("/updateUser")
    public String updateUser(User user){
        userService.updateUser(user);
        return "redirect:/user/all";//重定向
    }

    //删除用户的请求
    @RequestMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        userService.deleteUserById(id);
        return "redirect:/user/all";
    }

    //查询用户
    @RequestMapping("/selectUser")
    public String selectUser(String selectUserName,Model model){
        User user = userService.selectUserByName(selectUserName);
        List<User> userList = new ArrayList<>();
        userList.add(user);

        if(user == null){
            userList = userService.getAll();
            model.addAttribute("error","未查到");
        }


        model.addAttribute("allUser",userList);
        return "allUser";
    }

}

